<template>
  <el-dialog
    v-model="dialogVisible"
    title="条码打印"
    width="400px"
    :close-on-click-modal="false"
    :show-close="true"
  >
    <div class="barcode-form" style="background-color: rgb(175, 238, 238); padding: 20px;">
      <div class="code-list">
        <div class="code-item" @click="showCode('patient')">
          <el-button class="code-button">患者条形码</el-button>
        </div>
        <div class="code-item" @click="showCode('secondary')">
          <el-button class="code-button">患者二维码</el-button>
        </div>
        <div class="code-item" @click="showCode('urine')">
          <el-button class="code-button">小便二维码</el-button>
        </div>
        <div class="code-item" @click="showCode('stool')">
          <el-button class="code-button">大便二维码</el-button>
        </div>
      </div>

      <!-- 预览弹出框 -->
      <el-dialog
        v-model="previewVisible"
        :title="previewTitle"
        width="300px"
        append-to-body
        align-center
      >
        <div class="code-preview">
          <template v-if="currentPreview === 'patient'">
            <canvas ref="previewBarcode"></canvas>
            <div class="qr-preview">
              <QrcodeVue :value="form.patientBarcode" :size="150" level="H" />
            </div>
          </template>
          <template v-else>
            <QrcodeVue :value="getPreviewValue()" :size="200" level="H" />
          </template>
        </div>
      </el-dialog>

      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="success" @click="regenerateCodes">重新生成</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import QrcodeVue from 'qrcode.vue'
import JsBarcode from 'jsbarcode'

const dialogVisible = ref(false)
const previewVisible = ref(false)
const previewBarcode = ref(null)
const currentPreview = ref('')
const previewTitle = ref('')

const form = reactive({
  patientBarcode: '',
  patientSecondaryCode: '',
  urineSecondaryCode: '',
  stoolSecondaryCode: ''
})

let currentBedInfo = null

const emit = defineEmits(['confirm', 'cancel'])

// 生成随机字符串
const generateRandomString = (length) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 生成时间戳
const getTimestamp = () => {
  const now = new Date()
  return now.getFullYear().toString().slice(-2) +
    String(now.getMonth() + 1).padStart(2, '0') +
    String(now.getDate()).padStart(2, '0') +
    String(now.getHours()).padStart(2, '0') +
    String(now.getMinutes()).padStart(2, '0')
}

// 获取预览值
const getPreviewValue = () => {
  switch (currentPreview.value) {
    case 'secondary':
      return form.patientSecondaryCode
    case 'urine':
      return form.urineSecondaryCode
    case 'stool':
      return form.stoolSecondaryCode
    default:
      return form.patientBarcode
  }
}

// 显示码预览
const showCode = (type) => {
  currentPreview.value = type
  switch (type) {
    case 'patient':
      previewTitle.value = '患者条形码'
      break
    case 'secondary':
      previewTitle.value = '患者二维码'
      break
    case 'urine':
      previewTitle.value = '小便二维码'
      break
    case 'stool':
      previewTitle.value = '大便二维码'
      break
  }
  previewVisible.value = true
}

// 监听预览弹窗打开
watch(previewVisible, (newVal) => {
  if (newVal && currentPreview.value === 'patient') {
    setTimeout(() => {
      if (previewBarcode.value) {
        JsBarcode(previewBarcode.value, form.patientBarcode, {
          format: "CODE128",
          width: 2,
          height: 80,
          displayValue: true,
          fontSize: 14,
          textAlign: "center",
          textPosition: "bottom",
          textMargin: 6,
          font: "monospace",
          margin: 10
        })
      }
    }, 0)
  }
})

// 生成所有条码
const generateCodes = () => {
  if (!currentBedInfo) return

  const timestamp = getTimestamp()
  const randomId = generateRandomString(4)
  const bedNumber = currentBedInfo.bedNumber.replace('床', '')
  
  // 基础编码：床号(2位) + 时间戳(10位) + 随机码(4位)
  const baseCode = `${bedNumber.padStart(2, '0')}${timestamp}${randomId}`
  
  // 设置所有条码
  form.patientBarcode = baseCode
  form.patientSecondaryCode = baseCode
  form.urineSecondaryCode = baseCode
  form.stoolSecondaryCode = baseCode
}

// 重新生成条码
const regenerateCodes = () => {
  generateCodes()
}

const handleConfirm = () => {
  emit('confirm', form)
  dialogVisible.value = false
}

const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
}

const open = (bedInfo) => {
  currentBedInfo = bedInfo
  dialogVisible.value = true
  generateCodes()
}

defineExpose({
  open
})
</script>

<style scoped>
.barcode-form {
  border-radius: 4px;
}

.code-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.code-item {
  display: flex;
  justify-content: center;
}

.code-button {
  width: 100%;
  height: 40px;
  background-color: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.code-button:hover {
  background-color: #f5f7fa;
}

.code-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 10px;
}

.qr-preview {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}
</style> 